package com.lastcrdg.huaweiclock;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.blankj.utilcode.util.TimeUtils;

import java.text.SimpleDateFormat;
import java.util.Locale;

/**
 * author：liluo
 * e-mail：lastcrazysun@163.com
 * company：cusc
 * date：2017/9/29 16:43
 * description：
 */

public class ClockView extends View {

    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private Paint redPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private int width;
    private int height;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            invalidate();
        }
    };

    public ClockView(Context context) {
        super(context);
    }

    public ClockView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initPaint();
    }

    public ClockView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width = MeasureSpec.getSize(widthMeasureSpec);
        height = MeasureSpec.getSize(heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.translate(width / 2, height / 2);
        canvas.drawColor(Color.GRAY);
        for (int i = 0; i < 60; i++) {
            canvas.drawLine(0, -350, 0, -320, mPaint);
            canvas.rotate(360 / 60);
        }
        String time = TimeUtils.getNowString(new SimpleDateFormat("HH:mm", Locale.getDefault()));
        Rect bounds = new Rect();
        mPaint.getTextBounds(time, 0, time.length(), bounds);
        canvas.drawText(time, -1 * (bounds.right + bounds.left) / 2, -1 * (bounds.top + bounds.bottom) / 2, mPaint);
        drwaRedCircle(canvas);
    }

    double a = 0;
    private void drwaRedCircle(Canvas canvas) {
//        canvas.drawCircle(0, -270, 30, redPaint);
        canvas.drawCircle((float) (270*Math.sin(a)), (float)(-270*Math.cos(a)), 30, redPaint);
        a -= 360/60;
        mHandler.sendMessageDelayed(new Message(), 1000);

    }

    private void initPaint() {
        mPaint.setColor(Color.WHITE);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setTextSize(100);
        redPaint.setColor(Color.RED);
        redPaint.setStyle(Paint.Style.FILL);
    }

}
